﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Net;
using System.Web;
using System.Collections;

namespace Support
{
    public class HttpWebRequestHelper
    {
        /// <summary>
        /// 此字段没有定义为static静态全局变量，是为以后开发多线程发送做准备
        /// </summary>
        private CookieContainer m_cookieContainer = new CookieContainer();
        /// <summary>
        /// Cookie容器，先执行Login进行获取
        /// </summary>
        public CookieContainer cookieContainer
        {
            get 
            {
                if (HttpContext.Current.Session[Const.SHIPPING_TRACE_GET_VALIDATE_COOKIE] == null)
                {
                    return new CookieContainer();
                }
                else
                {
                    return (CookieContainer)HttpContext.Current.Session[Const.SHIPPING_TRACE_GET_VALIDATE_COOKIE];
                }
            }
            set 
            {
                HttpContext.Current.Session[Const.SHIPPING_TRACE_GET_VALIDATE_COOKIE] = value; 
            }
        }

        /// <summary>
        /// 执行HTTP POST请求。
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="parameters">请求参数</param>
        /// <returns>HTTP响应</returns>
        public string DoPost(string url, Dictionary<string, string> parameters)
        {
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.KeepAlive = true;
            req.UserAgent = "Top4Net";
            req.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
            req.CookieContainer = cookieContainer;

            byte[] postData = Encoding.UTF8.GetBytes(BuildPostData(parameters));
            Stream reqStream = req.GetRequestStream();
            reqStream.Write(postData, 0, postData.Length);
            reqStream.Close();

            HttpWebResponse rsp = (HttpWebResponse)req.GetResponse();
            Encoding encoding = Encoding.GetEncoding(rsp.CharacterSet);

            return GetResponseAsString(rsp, encoding);
        }

        /// <summary>
        /// 把响应流转换为文本。
        /// </summary>
        /// <param name="rsp">响应流对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>响应文本</returns>
        private static string GetResponseAsString(HttpWebResponse rsp, Encoding encoding)
        {
            StringBuilder result = new StringBuilder();
            Stream stream = null;
            StreamReader reader = null;

            try
            {
                // 以字符流的方式读取HTTP响应
                stream = rsp.GetResponseStream();
                reader = new StreamReader(stream, encoding);

                // 每次读取不大于256个字符，并写入字符串
                char[] buffer = new char[256];
                int readBytes = 0;
                while ((readBytes = reader.Read(buffer, 0, buffer.Length)) > 0)
                {
                    result.Append(buffer, 0, readBytes);
                }
            }
            finally
            {
                // 释放资源
                if (reader != null) reader.Close();
                if (stream != null) stream.Close();
                if (rsp != null) rsp.Close();
            }

            return result.ToString();
        }

        /// <summary>
        /// 组装普通文本请求参数。
        /// </summary>
        /// <param name="parameters">Key-Value形式请求参数字典</param>
        /// <returns>URL编码后的请求数据</returns>
        private static string BuildPostData(Dictionary<string, string> parameters)
        {
            StringBuilder postData = new StringBuilder();
            bool hasParam = false;

            IEnumerator<KeyValuePair<string, string>> dem = parameters.GetEnumerator();
            while (dem.MoveNext())
            {
                string name = dem.Current.Key;
                string value = dem.Current.Value;
                // 忽略参数名或参数值为空的参数
                if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(value))
                {
                    if (hasParam)
                    {
                        postData.Append("&");
                    }

                    postData.Append(name);
                    postData.Append("=");
                    postData.Append(Uri.EscapeDataString(value));
                    hasParam = true;
                }
            }

            return postData.ToString();
        }

        /// <summary>  
        /// 通过get方式请求页面，传递一个实例化的cookieContainer  
        /// </summary>  
        /// <param name="postUrl"></param> 
        /// <returns></returns>  
        public ArrayList GetHtmlData(string postUrl)
        {
            HttpWebRequest request;
            HttpWebResponse response;
            CookieContainer cookie = new CookieContainer();
            ArrayList list = new ArrayList();
            request = WebRequest.Create(postUrl) as HttpWebRequest;
            request.Method = "GET";
            request.UserAgent = "Mozilla/4.0";
            request.CookieContainer = cookieContainer;
            request.KeepAlive = true;

            request.CookieContainer = cookieContainer;
            try
            {
                //获取服务器返回的资源  
                using (response = (HttpWebResponse)request.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.Default))
                    {
                        foreach (Cookie ck in response.Cookies)
                        {
                            cookie.Add(ck);
                        }
                        if (cookie.Count > 0)
                        {
                            cookieContainer = cookie;
                        }
                        cookieContainer = cookie;
                        list.Add(cookie);
                        list.Add(reader.ReadToEnd());
                        list.Add(Guid.NewGuid().ToString());
                    }
                }
            }
            catch (WebException ex)
            {
                list.Clear();
                list.Add("ex");
                list.Add("发生异常：\n\r");
                WebResponse wr = ex.Response;
                using (Stream st = wr.GetResponseStream())
                {
                    using (StreamReader sr = new StreamReader(st, System.Text.Encoding.Default))
                    {
                        list.Add(sr.ReadToEnd());
                    }
                }
            }
            catch (Exception ex)
            {
                list.Clear();
                list.Add("ex");
                list.Add("发生异常：\n\r");
                list.Add(ex.Message);
            }
            return list;
        }  

        // <summary>  
        /// 下载验证码图片并保存到本地  
        /// </summary>  
        /// <param name="Url">验证码URL</param>  
        /// <param name="cookCon">Cookies值</param>  
        /// <param name="savePath">保存位置/文件名</param>  
        public string DownloadValidateImg(string Url)
        {
            string result = "";
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Url);
            CookieContainer cookie = new CookieContainer();
            //属性配置  
            webRequest.AllowWriteStreamBuffering = true;
            webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
            webRequest.MaximumResponseHeadersLength = -1;
            webRequest.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*";
            webRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)";
            webRequest.ContentType = "application/x-www-form-urlencoded";
            webRequest.Method = "GET";
            webRequest.Headers.Add("Accept-Language", "zh-cn");
            webRequest.Headers.Add("Accept-Encoding", "gzip,deflate");
            webRequest.KeepAlive = true;
            webRequest.CookieContainer = cookieContainer;
            try
            {
                string path = AppDomain.CurrentDomain.BaseDirectory + "downloads\\validate";
                if (!Directory.Exists(path))
                {
                    try
                    {
                        Directory.CreateDirectory(path);
                    }
                    catch
                    {
                        return "";
                    }
                }
                string fileName = DateTime.Now.Ticks.ToString() + ".jpg";
                string filePath = path + "\\" + fileName;
                result = "/downloads/validate/" + fileName;
                //获取服务器返回的资源  
                using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
                {
                    //cookie.Add(webResponse.Cookies);
                    //cookieContainer = cookie;
                    using (Stream sream = webResponse.GetResponseStream())
                    {
                        List<byte> list = new List<byte>();
                        while (true)
                        {
                            int data = sream.ReadByte();
                            if (data == -1)
                                break;
                            list.Add((byte)data);
                        }
                        File.WriteAllBytes(filePath, list.ToArray());
                    }
                }
            }
            catch (WebException ex)
            {
                result = "";
            }
            catch (Exception ex)
            {
                result = "";
            }
            return result;
        }  
    }
}
